/*
 * File Name : cd.cpp
 * Auther : dream.liuguobiao
 * Create Date : 2010-5-17
 * Last Edit : 2010-5-17
 */

#include <queue>
#include <string>
#include <iostream>

#include "file_system.h"
#include "user.h"
#include "my_string.h"
#include "cd.h"

cd::cd( std::string *new_parameters)
:command(new_parameters)
{
}

int cd::run_command(){
  file_system *system_point = get_shell_environment()->get_file_system();
  node *current_directory_tmp = system_point->get_current_directory();
  std::string *path = get_parameters();
  std::string current_path;
  my_string *string_tool = my_string::get_my_string();
  std::string path_tmp = *path;
  if(  ".." == *path ){
    node *father_piont = system_point->get_current_directory()->get_father() ;
    if( NULL != father_piont )system_point->set_current_directory(father_piont );
    return 0;
  }
  if( '/' != (*path)[0] ){
    std::string tmp = *(system_point->get_current_directory()->get_path() );
    current_path = tmp;
    if( "/" != tmp )
      current_path += "/";
  }
  current_path += *path;
  std::queue<std::string > *all_path = string_tool->split_string( '/' , current_path);
  node *current_node = system_point->get_root();
  system_point->set_current_directory( current_node );
  while(  !all_path->empty() ){
    current_node = system_point->find_node_just_current_directory( &all_path->front() );
    if( NULL == current_node ){
      system_point->set_current_directory( current_directory_tmp );
      std::cout<<"-bash: cd: "<<path_tmp<<" : no this file or directory\n";
      return 0;
    }
    all_path->pop();
    user *current_user = get_shell_environment()->get_login_users()->top();
    if( 4 != ( current_node->get_mod() & 4) && current_node->get_userID() != current_user->get_ID() ){
    std::cout<<"-bash: cd: "<<path_tmp<<": Permission denied\n";
    system_point->set_current_directory( current_directory_tmp );
    return 0;
}
    system_point->set_current_directory( current_node );
  }
  return 0;
}
